﻿
function sendFileToServer(formData, status, close) {
    
    var uploadURL = "/Upload/Upload";
    var extraData = {};
    var jqXHR = $.ajax({
        xhr: function () {
            var xhrobj = $.ajaxSettings.xhr();
            if (xhrobj.upload) {
                xhrobj.upload.addEventListener('progress', function (event) {
                    var percent = 0;
                    var position = event.loaded || event.position;
                    var total = event.total;
                    if (event.lengthComputable) {
                        percent = Math.ceil(position / total * 100);
                    }                    
                    status.setProgress(percent);                    
                }, false);
            }

            return xhrobj;
        },
        crossDomain: true,
        url: uploadURL,
        type: "POST",
        contentType: false,
        processData: false,
        cache: false,
        data: formData,
        success: function (data) {
            status.setProgress(100);            
            $.ajax({
                url: '/Home/Index/' + $('.apriboxparentfolder').last().attr("id"),
                dataType: 'html',
                success: function (data) {
                    
                    $('#main').html(data);
                }
            });

        }
    });

    status.setAbort(jqXHR);
}

var filesize;
var rowCount = 0;
function createStatusbar(obj) {
    rowCount++;
    var row = "odd";
    if (rowCount % 2 == 0) row = "even";
    this.statusbar = $("<div class='statusbar " + row + "'></div>");
    this.filename = $("<div class='filename'></div>").appendTo(this.statusbar);
    this.size = $("<div class='filesize'></div>").appendTo(this.statusbar);
    this.progressBar = $("<div class='progressBar'><div></div></div>").appendTo(this.statusbar);
    this.abort = $("<div class='abort'>Abort</div>").appendTo(this.statusbar);
    
    obj.prepend(this.statusbar);

    this.setFileNameSize = function (name, size) {
        var sizeStr = "";
        var sizeKB = size / 1024;
        if (parseInt(sizeKB) > 1024) {
            var sizeMB = sizeKB / 1024;
            sizeStr = sizeMB.toFixed(2) + " MB";
        }
        else {
            sizeStr = sizeKB.toFixed(2) + " KB";
        }

        this.filename.html(name);
        this.size.html(sizeStr);
    }
    this.setProgress = function (progress) {
        var progressBarWidth = progress * this.progressBar.width() / 100;
        this.progressBar.find('div').animate({ width: progressBarWidth }, 10).html(progress + "% ");
        if (parseInt(progress) >= 100) {
            this.abort.hide();
            
        }
    }
    this.setAbort = function (jqxhr) {
        var sb = this.statusbar;
        this.abort.click(function () {
            jqxhr.abort();
            sb.hide();
        });
    }
}
function handleFileUpload(files) {
    for (var i = 0; i < files.length; i++) {
       
        var allow = $('#AllowedSize').attr("value");
        var currentfilesize =files[i].size/1024/1024;
        //alert(allow-currentfilesize);
       
       
        if ((allow - currentfilesize) > 0) {
            // alert(allow);
            if ($('.progressbar').is(':visible'))
                OnUp();
            else $('.progressbar').fadeIn();

            var fd = new FormData();
            if (files[i] != null) {
                fd.append('file', files[i]);
                fd.append('folderId', $('.apriboxparentfolder').last().attr('id'));
                filesize = files[i].size;
                allow = true;
                var status = new createStatusbar($('.loadcontent'));
                status.setFileNameSize(files[i].name, files[i].size);

                if (i == files.length - 1)
                    close = true;
                sendFileToServer(fd, status, close);

            }
        }
        else

        {
            SpaceEndidPopUp();

        }

    }
}


function OnDown() {
    $('#down').fadeOut('fast');
    $('#up').fadeIn('fast');
    $('.progressbar').animate({
        'margin-top': '798px',
        height: 20,
        'border-radius': '0',
        width: 195
    });
    $('.phead').animate({
        height: 20,
        'border-radius': '0',
        width: 195
    });
    $('.loadcontent').animate({
        height: 0                
    });
}

function OnUp() {
    $('#up').fadeOut('fast');
    $('#down').fadeIn('fast');

    $('.progressbar').animate({
        'margin-top': '665px',
        height: 150,  
        width: 517
    });
    $('.phead').animate({
        height: 20,
        width: 517
    });
    $('.loadcontent').animate({
        'height': '85%'
    });
}


//----------------------------------------------------document ready

$(document).ready(function () {


    //------------------------------------------------------------------------------------progress bar

    $('#down').click(OnDown);

    $('#up').click(OnUp);


    $('#exiticon').click(function () {
        $('.progressbar').fadeOut();
    });




    


    $('.progressbar').resizable({
        maxHeight: 600,
        maxWidth: 735,
        minHeight: 250,
        minWidth: 635
    });
    // -----------------------------------------------------------добавляем действие на дроп
    var dndview = $('#dndview');
    var backlight = $('#backlight');

    dndview.on('dragenter', function () {

       
        backlight.show();
    });

    backlight.on('dragleave', function () {
        $(this).hide();
    });

    $(document).on('dragenter', function (e) {
        e.stopPropagation();
        e.preventDefault();
    });
    $(document).on('dragover', function (e) {
        e.stopPropagation();
        e.preventDefault();
    });
    $(document).on('drop', function (e) {
        e.stopPropagation();
        e.preventDefault();
    });

    
    var target = document.getElementById('dndview');
    target.addEventListener('drop', function (e) {

        
        backlight.hide();
        e.preventDefault();

        var files = e.dataTransfer.files;

        if (files[0] != null) {

           handleFileUpload(files);
        }
        

    }, false);
    

});









//Функция для вызова попапа когда кончаеться место!!!(место у пользователя на АприБоксе)!!!!
function SpaceEndidPopUp() {


    popupwindow = $('#popup1').bPopup({

        easing: 'easeOutBack',
        speed: 1050,
        transition: 'slideDown',
        autoClose: 3000
    });



}